package cn.iocoder.yudao.module.erp.controller.admin.costinfo;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.db.TenantBaseDO;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.sale.vo.order.ErpSaleOrderRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.accountinfo.AccountInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.customerinfo.CustomerInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpCustomerDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleOrderDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.sale.ErpSaleOrderItemDO;
import cn.iocoder.yudao.module.erp.dal.mysql.accountinfo.AccountInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.costinfo.CostInfoMapper;
import cn.iocoder.yudao.module.erp.service.customerinfo.CustomerInfoService;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMultiMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

import cn.iocoder.yudao.module.erp.controller.admin.costinfo.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.costinfo.CostInfoDO;
import cn.iocoder.yudao.module.erp.service.costinfo.CostInfoService;

@Tag(name = "管理后台 - 其他费用")
@RestController
@RequestMapping("/erp/cost-info")
@Validated
public class CostInfoController {

    @Resource
    private CostInfoService costInfoService;

    @Resource
    private CostInfoMapper costInfoMapper;

    @Resource
    private AccountInfoMapper accountInfoMapper;

    @Resource
    private CustomerInfoService customerInfoService;

    @PostMapping("/create")
    @Operation(summary = "创建其他费用")
    @PreAuthorize("@ss.hasPermission('erp:cost-info:create')")
    public CommonResult<Long> createCostInfo(@Valid @RequestBody CostInfoSaveReqVO createReqVO) {
        return success(costInfoService.createCostInfo(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新其他费用")
    @PreAuthorize("@ss.hasPermission('erp:cost-info:update')")
    public CommonResult<Boolean> updateCostInfo(@Valid @RequestBody CostInfoSaveReqVO updateReqVO) {
        costInfoService.updateCostInfo(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除其他费用")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:cost-info:delete')")
    public CommonResult<Boolean> deleteCostInfo(@RequestParam("id") Long id) {
        costInfoService.deleteCostInfo(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得其他费用")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:cost-info:query')")
    public CommonResult<CostInfoRespVO> getCostInfo(@RequestParam("id") Long id) {
        CostInfoDO costInfo = costInfoService.getCostInfo(id);
        return success(BeanUtils.toBean(costInfo, CostInfoRespVO.class));
    }


    @GetMapping("/getCostTypeList")
    @Operation(summary = "获得其他费用")
    public CommonResult<List<CostTypeRespVO>> getCostTypeList() {
      //  CostInfoDO costInfo = costInfoService.getCostInfo(id);
        List<CostInfoDO> typeList=costInfoMapper.selectList(new LambdaQueryWrapperX<CostInfoDO>().select(CostInfoDO::getType).groupBy(CostInfoDO::getType));


        return success(BeanUtils.toBean(typeList, CostTypeRespVO.class,type -> {
            type.setValue(type.getType());
        }));
    }




    @GetMapping("/findCostListByAccountId")
    @Operation(summary = "获得其他费用分页")
    public CommonResult<List<CostInfoRespVO>> findCostListByAccountId(CostInfoPageReqVO pageReqVO) {
      /*  List<CostInfoRespVO> list = buildSaleOrderVOPageResult(costInfoService.getCostInfoPage(pageReqVO)).getList();*/
        //获得当前账户已存在且未配置的
        AccountInfoDO account=accountInfoMapper.selectById(pageReqVO.getAccountId());
        if(account==null){
            throw exception(new ErrorCode(1_1_1_1_2,"参数错误，请刷新后再试！"));
        }
        List<CostInfoDO> list=costInfoMapper.selectList(new LambdaQueryWrapperX<CostInfoDO>().eq(CostInfoDO::getCustomerId,pageReqVO.getCustomerId()).and(cs->cs.eq(CostInfoDO::getAccountId,pageReqVO.getAccountId()).or()
                .isNull(CostInfoDO::getAccountId)));

        return success(buildList(list));
    }


    @GetMapping("/page")
    @Operation(summary = "获得其他费用分页")
    @PreAuthorize("@ss.hasPermission('erp:cost-info:query')")
    public CommonResult<PageResult<CostInfoRespVO>> getCostInfoPage(@Valid CostInfoPageReqVO pageReqVO) {
        PageResult<CostInfoDO> pageResult = costInfoService.getCostInfoPage(pageReqVO);
       // return success(BeanUtils.toBean(pageResult, CostInfoRespVO.class));
        return success(buildSaleOrderVOPageResult(pageResult));
    }



    @GetMapping("/export-excel")
    @Operation(summary = "导出其他费用 Excel")
    @PreAuthorize("@ss.hasPermission('erp:cost-info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportCostInfoExcel(@Valid CostInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {

        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CostInfoRespVO> list = buildSaleOrderVOPageResult(costInfoService.getCostInfoPage(pageReqVO)).getList();
        // 导出 Excel
        ExcelUtils.write(response, "其他费用.xls", "数据", CostInfoRespVO.class,list
                        /*BeanUtils.toBean(list, CostInfoRespVO.class)*/);
    }


    private PageResult<CostInfoRespVO> buildSaleOrderVOPageResult(PageResult<CostInfoDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }

        // 客户信息
        List<Long> customerIds=pageResult.getList().stream().map(CostInfoDO::getCustomerId).collect(Collectors.toList());
        Map<Long,CustomerInfoDO> customerMap=new HashMap<>();
        if(customerIds!=null&&customerIds.size()>0){
            List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(customerIds);
            customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));
        }

        PageResult<CostInfoRespVO> rpage=BeanUtils.toBean(pageResult, CostInfoRespVO.class);

        for(CostInfoRespVO cost:rpage.getList()){
            MapUtils.findAndThen(customerMap, cost.getCustomerId(), supplier -> cost.setCustomerName(supplier.getName()));
        }


        return rpage;
    }


    private List<CostInfoRespVO> buildList(List<CostInfoDO> list) {
        if (CollUtil.isEmpty(list)) {
            return null;
        }

        // 客户信息
        List<Long> customerIds=list.stream().map(CostInfoDO::getCustomerId).collect(Collectors.toList());
        Map<Long,CustomerInfoDO> customerMap=new HashMap<>();
        if(customerIds!=null&&customerIds.size()>0){
            List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(customerIds);
            customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));
        }

        List<CostInfoRespVO> rpage=BeanUtils.toBean(list, CostInfoRespVO.class);

        for(CostInfoRespVO cost:rpage){
            MapUtils.findAndThen(customerMap, cost.getCustomerId(), supplier -> cost.setCustomerName(supplier.getName()));
        }


        return rpage;
    }

}